package cn.uai.activiti8.approval.cmd;

import org.activiti.bpmn.model.FlowElement;
import org.activiti.bpmn.model.Process;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.impl.util.ProcessDefinitionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @desc 驳回到当前节点前的 任意节点
 * @author uai
 * @since 2025/7/18 23:50
 * @version 1.0
 */
public class Reject2AnyNodeCmd extends AbstractRejectCmd<Void> {

    private static final long serialVersionUID = 7156123379310329514L;

    private static final Logger LOGGER = LoggerFactory.getLogger(Reject2AnyNodeCmd.class);

    /**
     * 驳回到目的节点 activityId
     */
    private String targetActivityId;

    public Reject2AnyNodeCmd(String taskId, String targetActivityId) {
        super(taskId);
        this.targetActivityId = targetActivityId;
    }

    @Override
    protected Void execute(CommandContext commandContext, TaskEntity task) {
        ExecutionEntity execution = task.getExecution();
        Process process = ProcessDefinitionUtil.getProcess(task.getProcessDefinitionId());
        FlowElement targetFlowElement = process.getFlowElement(getTargetActivityId());
        execution.setVariable("isPass", false);
        execution.setVariable("actionType", 3);
        execution.setCurrentFlowElement(targetFlowElement);
        LOGGER.info("驳回到指定节点：Node: [targetActivityId: {}, name: {}]", getTargetActivityId(), targetFlowElement.getName());
        commandContext.getAgenda().planContinueProcessOperation(execution);

        // 删除 act_ru_task 中的数据
        task.setExecutionId(null);
        commandContext.getTaskEntityManager().deleteTask(task.getId(), "驳回至任意节点", false);
        // 删除任务还可以用下面这个
        // commandContext.getTaskEntityManager().deleteTask(taskEntity, null, false, false);

        return null;
    }

    public String getTargetActivityId() {
        return targetActivityId;
    }

    public void setTargetActivityId(String targetActivityId) {
        this.targetActivityId = targetActivityId;
    }
}
